import store from '@/store'
import axios from '@/utils/api.request'

const authorize = function (state, appid) {
    // 目标url编码
    state = encodeURIComponent(state)
    // 中间页
    const redirectUrl = config.axiosConfig.urlPrefix.apiUrl + config.routerConfig.routerPath.wxRedirect;
    /**
     * 判断是否需要授权 获取链接中的appid换取wxappid
     * 跳转微信授权
     */

    getWxAppid(appid);

    function getCode(state, wxappid) {
        window.localStorage.setItem('wxappid', wxappid);
        window.localStorage.setItem('appId', appId);
        window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + wxappid + "&redirect_uri=" + redirectUrl + "&response_type=code&scope=snsapi_base&state=" + state + "#wechat_redirect"
    }

    function getWxAppid(appid) {
        axios.request({
            url: '/login/oauth2/getAppInfo',
            methods: 'post',
            data: {
                appid
            }
        }).then(res => {
            console.log(res)
            if (res.code == 0) {
                let wxAppId = res.data.appId;
                window.localStorage.setItem('wxAppId', wxAppId)
                getCode(state, wxAppId)
            }
        }).catch(err => {
            console.log(err)
        })
    }
}

export default authorize